import os
from importlib import import_module, util
import requests
from RPA.Browser.Playwright import Playwright
from urllib.parse import urlparse, urlunparse, parse_qs, urlencode
import sso_auth as sso

COMMON_PATH = os.environ["COMMON_PATH"]
printer = import_module("printer").IndentPrinter(indent=3)

browser = Playwright()
browser.new_browser()
browser.new_page(url="about:blank")


# 提取 cookies 中的鉴权信息
def extract_cookies(cookies):
    try:
        extracted_cookies = {"currentRegion": "sz"}
        for cookie in cookies:
            if cookie["name"] in ["route", "token", "onlyCookie", "JSESSIONID"]:
                extracted_cookies[cookie["name"]] = cookie["value"]
        return extracted_cookies
    except Exception as e:
        printer(f"[发生错误] 提取cookies: {e}")
        raise e


# 提取 Authorization 信息
def get_authorization_token(cookies):
    try:
        for cookie in cookies:
            if cookie["name"] == "eastcom-jk-token":
                return f"Bearer {cookie['value']}"
        return None
    except Exception as e:
        printer(f"[发生错误] 获取授权信息: {e}")
        raise e


def get_browser_cookies(auth_url):
    try:

        browser.go_to(auth_url)
        browser.wait_for_elements_state("id=bs-example-navbar-collapse-1")
        cookies = browser.get_cookies()
        extracted_cookies = extract_cookies(cookies)
        return {
            "cookies": extracted_cookies,
            "browser": browser,
        }

    except Exception as e:
        printer(f"[发生错误] 获得cookies: {e}")
        raise e


def main():
    printer("[sso登录] 开始")
    printer("[sso登录] 登录鉴权")
    auth_url = sso.login(
        browser,
        "sg_gmcc_net",
        "http://sf.gmcc.net:27001/oauth/token",
        "dongzhibao",
        "Gmcc999+",
    )
    printer("[sso登录] 获得cookies")
    auth = get_browser_cookies(auth_url)
    printer.add(-1)
    printer("[sso登录] 完成")
    return auth


if __name__ == "__main__":
    main()
